<template>
  <div class="user-list-container">
    <!-- 查询表单 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="搜索" prop="username">
              <el-input
                placeholder="订单编号、收货人名称、收货人手机号、快递/物流单号"
                v-model="queryParams.search"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单状态" prop="order_status">
              <el-select
                v-model="queryParams.order_status"
                placeholder="请选择订单状态"
                clearable
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6" style="text-align: right">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
          v-loading="loading"
          :data="tableData"
          border
        class="table"
        >
          <el-table-column prop="order_id" label="ID" width="80" fixed />
          <el-table-column prop="order_sn" label="订单编号" width="240" fixed />
          <el-table-column prop="tracking_sn" label="快递/物流单号" width="220" />
          <el-table-column prop="recipient_name" label="收货人名称"  />
          <el-table-column label="收货人手机号">
            <template #default="scope">
              {{ encryptPhone(scope.row.phone_number) }}
            </template>
          </el-table-column>
          <el-table-column prop="province_name" label="省名称"  />
          <el-table-column prop="city_name" label="市名称" />
          <el-table-column prop="area_name" label="区名称"  />
          <el-table-column prop="street_address" label="收货地址" width="200" />
          <el-table-column prop="total_price" label="订单金额"  />
          <el-table-column prop="order_over_at" label="订单结束时间"  width="200"/>
          <el-table-column prop="order_status" label="订单状态" >
            <template #default="scope">
              {{ formatStatus(scope.row.order_status) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <el-button link @click="handleView(scope.row)">查看</el-button>
              <el-button 
                v-if="scope.row.order_status === 10" 
                link 
                type="primary" 
                @click="handleDelivery(scope.row)"
              >
                订单发货
              </el-button>
              <template v-if="scope.row.order_status === -1">
                <el-button 
                  link 
                  type="success" 
                  @click="handleApproveRefund(scope.row)"
                >
                  通过
                </el-button>
                <el-button 
                  link 
                  type="danger" 
                  @click="handleRejectRefund(scope.row)"
                >
                  拒绝
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </el-card>

    <!-- 查看对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="订单详情"
      width="800"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单ID">{{ currentRow.order_id }}</el-descriptions-item>
        <el-descriptions-item label="订单编号">{{ currentRow.order_sn }}</el-descriptions-item>
        <el-descriptions-item label="快递单号">{{ currentRow.tracking_sn }}</el-descriptions-item>
        <el-descriptions-item label="收货人">{{ currentRow.recipient_name }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ encryptPhone(currentRow.phone_number) }}</el-descriptions-item>
        <el-descriptions-item label="收货地址">
          {{ currentRow.province_name }} {{ currentRow.city_name }} {{ currentRow.area_name }} {{ currentRow.street_address }}
        </el-descriptions-item>
        <el-descriptions-item label="订单金额">{{ currentRow.total_price }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">{{ formatStatus(currentRow.order_status) }}</el-descriptions-item>
        <el-descriptions-item label="订单结束时间">{{ currentRow.order_over_at }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="deliveryDialogVisible"
      title="订单发货"
      width="500"
    >
      <el-form :model="deliveryForm" label-width="100px">
        <el-form-item label="订单编号">
          <el-input v-model="currentRow.order_sn" disabled />
        </el-form-item>
        <el-form-item label="物流单号" prop="tracking_sn">
          <el-input v-model="deliveryForm.tracking_sn" placeholder="请输入物流单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="deliveryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelivery">确认发货</el-button>
      </template>
    </el-dialog>

    <!-- 退款拒绝对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝退款"
      width="500"
    >
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="订单编号">
          <el-input v-model="currentRow.order_sn" disabled />
        </el-form-item>
        <el-form-item label="订单金额">
          <el-input v-model="currentRow.total_price" disabled />
        </el-form-item>
        <el-form-item label="拒绝原因" prop="reject_reason">
          <el-input 
            v-model="rejectForm.reject_reason" 
            type="textarea" 
            placeholder="请输入拒绝退款原因" 
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReject">确认拒绝</el-button>
      </template>
    </el-dialog>

    <!-- 退款通过对话框 -->
    <el-dialog
      v-model="approveDialogVisible"
      title="通过退款"
      width="500"
    >
      <el-form :model="approveForm" label-width="100px" :rules="approveRules">
        <el-form-item label="订单编号">
          <el-input v-model="currentRow.order_sn" disabled />
        </el-form-item>
        <el-form-item label="退款金额" prop="refund_amount">
          <el-input-number
            v-model="approveForm.refund_amount"
            :min="0.01"
            :max="currentRow.total_price"
            :precision="2"
            :controls="false"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmApprove">确认通过</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import tableMixin from "@/mixins/tableMixin";
import api from "@/request/api.js";

export default {
  name: "UserList",
  mixins: [tableMixin],
  data() {
    return {
      companyChildList: {},
      //查询参数
      queryParams: { 
        search: '',
        order_status: null
      },
      apimodel: "jifengood",
      apival: "orderList",
      // 状态选项
      statusOptions: [
        { value: -66, label: "全部" },
        { value: 0, label: "待支付" },
        { value: 10, label: "已支付" },
        { value: -1, label: "申请退款" },
        { value: -2, label: "拒绝退款" },
        { value: 4, label: "待收货" },
        { value: -10, label: "已退款" },
        { value: 20, label: "订单已完成" },
        { value: -20, label: "已取消" }
      ],
      viewDialogVisible: false,
      deliveryDialogVisible: false,
      rejectDialogVisible: false,
      approveDialogVisible: false,
      currentRow: {},
      deliveryForm: {
        tracking_sn: ''
      },
      rejectForm: {
        reject_reason: ''
      },
      approveForm: {
        refund_amount: 0
      },
      approveRules: {
        refund_amount: [
          { required: true, message: '请输入退款金额', trigger: 'blur' },
          { type: 'number', min: 0.01, max: Infinity, message: '退款金额必须大于0.01', trigger: 'blur' }
        ]
      },
      form: {
        image_url: "",
        link_url: "",
        banner_title: "",
        sort_order: 0,
      },
      rules: {},
      companys: [],
      orderInfo: {},
    };
  },
  mounted() {
  },
  methods: {
    // 手机号加密
    encryptPhone(phone) {
      if (!phone) return '';
      return phone.replace(/(\d{3})\d*(\d{4})/, '$1****$2');
    },
    
    // 格式化状态显示
    formatStatus(status) {
      const item = this.statusOptions.find(item => item.value === status);
      return item ? item.label : status;
    },
    
    // 查看订单详情
    handleView(row) {
      this.currentRow = row;
      this.viewDialogVisible = true;
    },

    // 订单发货
    handleDelivery(row) {
      this.currentRow = row;
      this.deliveryForm.tracking_sn = row.tracking_sn || '';
      this.deliveryDialogVisible = true;
    },

    // 确认发货
    confirmDelivery() {
      if (!this.deliveryForm.tracking_sn) {
        this.$message.warning('请输入物流单号');
        return;
      }
      
      api.jifengood
        .integralOrderSave({ 
          order_id: this.currentRow.order_id, 
          tracking_sn: this.deliveryForm.tracking_sn 
        })
        .then((res) => {
          if (res?.status == 200) {
            this.$message.success("发货成功");
            this.deliveryDialogVisible = false;
            this.getTableData();
          }
        });
    },

    // 处理拒绝退款
    handleRejectRefund(row) {
      this.currentRow = row;
      this.rejectForm.reject_reason = '';
      this.approveForm.refund_amount = row.total_price;
      this.rejectDialogVisible = true;
    },

    // 确认拒绝退款
    confirmReject() {
      if (!this.rejectForm.reject_reason) {
        this.$message.warning('请输入拒绝原因');
        return;
      }
      
      api.jifengood
        .refundReject({
          order_sn: this.currentRow.order_sn,
          order_status:-2,
          reason_rejection: this.rejectForm.reject_reason,
          refund_total:this.approveForm.refund_amount
        })
        .then((res) => {
          if (res?.status == 200) {
            this.$message.success("已成功拒绝退款");
            this.rejectDialogVisible = false;
            this.getTableData();
          }
        });
    },

    // 处理通过退款
    handleApproveRefund(row) {
      this.currentRow = row;
      this.approveForm.refund_amount = row.total_price;
      this.approveDialogVisible = true;
    },

    // 确认通过退款
    confirmApprove() {
      if (this.approveForm.refund_amount < 0.01 || this.approveForm.refund_amount > this.currentRow.total_price) {
        this.$message.warning('退款金额必须在0.01和订单总金额之间');
        return;
      }
      
      api.jifengood
        .refundReject({
          order_sn: this.currentRow.order_sn,
          order_status:-10,
          reason_rejection: '',
          refund_total:this.approveForm.refund_amount
        })
        .then((res) => {
          if (res?.status == 200) {
            this.$message.success("退款已通过");
            this.approveDialogVisible = false;
            this.getTableData();
          }
        });
    },

    // 加载公司数据
    handleCloseAddDialog() {
      this.dialogVisible = false;
      this.dialogType = "";
      this.form = {
        tag_name: "",
        is_type: "",
      };
      this.resetForm();
    },

    // 删除
    handleDelete(row) {
      this.$confirm("确认删除吗?", "提示", {
        type: "warning",
      })
        .then(async () => {
          api.banner
            .del({
              tag_id: row.tag_id,
            })
            .then((res) => {
              if (res?.status == 200) {
                this.$message.success("删除成功");
                this.getTableData();
              }
            });
        })
        .catch(() => {});
    },

    resetForm() {
      this.$refs.formRef.resetFields();
    },

    //选择地点
    handleRegionChange(val) {
      this.form.province_id = val.province;
      this.form.city_id = val.city;
      this.form.area_id = val.district;
    },
  },
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.table-card {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>